import Map from 'ol/Map'
import View from 'ol/View'
import Layer from 'ol/layer/Layer' // 瓦片加载器
import TileLayer from 'ol/layer/Tile'
import Feature from 'ol/Feature.js'

import Point from 'ol/geom/Point.js'
import GeoJSON from 'ol/format/GeoJSON'
import VectorLayer from 'ol/layer/Vector'
import { TileWMS, OSM, ImageArcGISRest } from 'ol/source'
import TileGrid from 'ol/tilegrid/TileGrid'
import TileImage from 'ol/source/TileImage'
import VectorSource from 'ol/source/Vector'
import { fromExtent } from 'ol/geom/Polygon.js'
import { TileArcGISRest, XYZ, ImageTile } from 'ol/source.js'
// import {ImageArcGISRest, OSM} from 'ol/source.js';
// import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer.js';
import { Group as LayerGroup, Image as ImageLayer } from 'ol/layer.js'
import VectorImageLayer from 'ol/layer/VectorImage.js'
import { Circle, Fill, Icon, Stroke, Style, Text } from 'ol/style.js'
import { fromLonLat, toLonLat, transform, transformExtent } from 'ol/proj'
import { get } from 'ol/proj'
import Mask from 'ol-ext/filter/Mask'
import Crop from 'ol-ext/filter/Crop'
import * as maputils from './maputils'
import * as onemap from '../onemap'
import config from '../../config/index'

import proj4 from 'proj4';
import { Projection } from 'ol/proj';
import { register } from 'ol/proj/proj4';

//
//地图

let map

//
//地图
const initMap = (options) => {

  map = new Map({
    target: options.map,
    view: new View({
      center: transform([113.304788, 28.013391], 'EPSG:4326', 'EPSG:3857'),
      zoom: 4,
      // projection:projection
    })
  })
  //
  // addTestMapLayer();
    // test12();
    // test125();
    // test123();
  //
  window.map = map
  MapManager.getInstance().loadMapSource(options.maplayer || 'tianditu-vec')

  return map
}

//单个地震地图
const initOtherMap = (map) => {

  const projection = get('EPSG:3857')
  const layer =  new TileLayer({
    id: 'ditu-1',
    source: new XYZ({
      projection: projection,
      url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
      crossOrigin: 'anonymous',
      wrapX: false
    })
  })
  const maps = new Map({
    target: map,
    view: new View({
      center: transform([113.304788, 28.013391], 'EPSG:4326', 'EPSG:3857'),
      zoom: 4,
    })
  })

  maps.addLayer(layer)

  // MapManager.getInstance().loadMapSource(layer|| 'tianditu')
  return maps
}



//获取地震基本信息
const loadEarthQuake = () => {}

const addTestMapLayer = () => {
  const url =
    'http://10.13.155.199:8090/iserver/services/map-dzyjzhjsptCommon/arcgisrest/setting_seismic_influenceflied_mian@dzyjzhjspt_proper_guojia/MapServer'
  const layers = map.getLayers().getArray()
  const supermaplayer = new ImageLayer({
    source: new ImageArcGISRest({
      ratio: 1,
      params: {
        LAYER: '0' // 具体的图层名
        // 'DDD': '1' // 仅加载属性 ddd=1 的数据
      },
      url: url
    })
  })
  map.addLayer(supermaplayer)



  return

  map.addLayer(supermaplayer)
}

function test12() {
  const layers = map.getLayers().getArray()
  const supermaplayer = new TileLayer({
    id: 'setting_seismic_influenceflied',
    zIndex: 999,
    source: new TileWMS({
      // url: 'http://10.5.92.115:8090/iserver/services/map-dzyjzhjsptCommon-2/wms130/dzyjzhjspt_proper_guojia',
      url:'http://10.5.92.115:8090/iserver/services/map-test241022/wms130/setting_seismic_influenceflied11%40test201022',
      params: {
        LAYERS: '0.0',
        FORMAT: 'image/png',
        layerDefs: JSON.stringify({
          0.0: 'earth_quake_id = 10022'
        })
      },
      attributions: '</span>'
    })
  })
  map.addLayer(supermaplayer)
}

function test125() {
  const layers = map.getLayers().getArray()
  const supermaplayer = new TileLayer({
    id: 'setting_seismic_influenceflied1',
    zIndex: 999,
    source: new TileWMS({
      url: 'http://10.5.92.115:8090/iserver/services/map-dzyjzhjsptCommon-3/wms130/setting_seismic_influenceflied_mian@dzyjzhjspt_proper_guojia',
      params: {
        LAYERS: '0.0',
        FORMAT: 'image/png',
        layerDefs: JSON.stringify({
          ['0.0']: 'earth_quake_id = 10022'
        })
      },
      attributions: '</span>'
    })
  })
  map.addLayer(supermaplayer)
}
function test123() {
  const layers = map.getLayers().getArray()
  const supermaplayer = new TileLayer({
    id: 'setting_seismic_influenceflied',
    zIndex: 999,
    source: new TileWMS({
      url: 'http://10.13.155.199:8090/iserver/services/map-dzyjzhjsptCommon-2/wms111/dzyjzhjspt_proper_guojia',
      params: {
        LAYERS: '0.4',
        FORMAT: 'image/png',
        layerDefs: JSON.stringify({
          0.4: 'earth_quake_id = 624'
        })
      },
      attributions: '</span>'
    })
  })
  map.addLayer(supermaplayer)
}
//kspgyxcm
//setting_seismic_influenceflied
//获取地震影响场
let EarthQuakeYXC = {}

//添加需要过滤的wms图层
const loadFilterLayer = (id, mapLayer) => {
  // console.info(id,laycode + 'ddddddddddddd')
 
  var myLayer = new TileLayer({
    opacity: 0.7,
    source: new TileWMS({
      url: config.SUPERMAPURL+"/dzyjzhjspt_proper_guojia",
      params: {
        LAYERS: mapLayer.layerUrl,
        FORMAT: 'image/png',
        layerDefs: JSON.stringify({
          [mapLayer.layerUrl]: `earth_quake_id=${id}`
        })
      },
      attributions: '</span>'
    })
  })
  map.addLayer(myLayer)
  EarthQuakeYXC[mapLayer.layerCode] = myLayer
}

const loadEarthQuakeYXC = (id, laycode,version) => {
  // id=624;
  var query = {
    tableName: 'setting_seismic_influenceflied',
    fields:
      'uuid,earthquake_level,dz_intensity,long_x,short_y,data_source,remark,earth_quake_id,operate_time,trigger_type,model_id,category,operate_user_id,operate_dept_id,version,type,code,angle,intensity_show,intensity_china_show,area',
       filter: `earth_quake_id='${id}' AND version='${version}' `
  }
  onemap.listGeoJsonByTable(query).then((res) => {
    var geojson = JSON.parse(res.geodata.value)
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson)
    })

    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
      let style
      if (feature.get('property1') === 'valueA') {
        style = new Style({
          fill: new Fill({
            color: 'rgba(0, 255, 0, 0.5)'
          }),
          stroke: new Stroke({
            color: 'rgba(0, 255, 0, 1)',
            width: 1
          })
        })
      } else if (feature.get('property2') === 'valueB') {
        style = new Style({
          fill: new Fill({
            color: 'rgba(0, 0, 255, 0.5)'
          }),
          stroke: new Stroke({
            color: 'rgba(0, 0, 255, 1)',
            width: 1
          })
        })
      } else {
        style = new Style({
          fill: new Fill({
            color: 'rgba(254, 229, 230, 0.5)'
          }),
          stroke: new Stroke({
            color: 'rgba(0, 0, 0, 1)',
            width: 1
          })
        })
      }
      feature.setStyle(style)
    })
    map.addLayer(tmpLayer)
    EarthQuakeYXC[laycode] = tmpLayer
    console.log(EarthQuakeYXC[laycode])

    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}

const delEarthQuakeYXC = (laycode) => {
  console.log(EarthQuakeYXC[laycode], laycode)

  map.removeLayer(EarthQuakeYXC[laycode])
}

const allLayers = [
  { id: 'tdtdtlayer', name: '地图', type: 'TileLayer', visible: false },
  { id: 'tdtyxlayer', name: '影像', type: 'TileLayer', visible: false },
  { id: 'tdtbzlayer', name: '标注', type: 'TileLayer', visible: false },
  {
    id: 'guolayer',
    name: '国边界',
    type: 'VectorLayer',
    visible: true
  },

  {
    id: 'shenglayer',
    name: '省边界',
    type: 'VectorImageLayer',
    visible: false
  },
  {
    id: 'shilayer',
    name: '市边界',
    type: 'VectorImageLayer',
    visible: false
  },
  // {
  //   id: "xianlayer",
  //   name: "区县边界",
  //   type: "VectorImageLayer",
  //   visible: false,
  // },
  {
    id: 'szysjqlayer',
    name: '水资源三级区',
    type: 'VectorImageLayer',
    visible: false
  },
  {
    id: 'szysijqlayer',
    name: '水资源四级区',
    type: 'VectorImageLayer',
    visible: false
  },
  {
    id: 'sxlayer',
    name: '水系分区',
    type: 'VectorImageLayer',
    visible: true
    // childrens: [
    //   {
    //     id: "sximglayer",
    //     name: "水系分区地图",
    //     type: "VectorImageLayer",
    //     visible: true,
    //   },
    //   {
    //     id: "sxlabellayer",
    //     name: "水系分区标注",
    //     type: "VectorImageLayer",
    //     visible: true,
    //   },
    // ],
  },
  { id: 'hplayer', name: '湖泊', type: 'VectorImageLayer', visible: false },
  { id: 'sklayer', name: '水库', type: 'VectorImageLayer', visible: false },
  { id: 'hllayer', name: '河流', type: 'VectorImageLayer', visible: true },
  { id: 'dflayer', name: '堤防', type: 'VectorImageLayer', visible: false },
  { id: 'szlayer', name: '水闸', type: 'VectorImageLayer', visible: false },
  { id: 'jczlayer', name: '监测站', type: 'VectorImageLayer', visible: false }
]

const loadAllLayers = async (ol2d) => {
  await maputils.LoadBaseLayers({ ol2d: ol2d, allLayers: allLayers })

  var tdtdt = ol2d.getLayerById('tdtdtlayer')
  if (tdtdt) {
    tdtdt.setSource(
      new XYZ({
        wrapX: false,
        url: 'http://mapcache.tsingnormal.com:6688/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=50b117fa2f96eb1bf7c84b1365c2b548'
      })
    )
  }

  var tdtyx = ol2d.getLayerById('tdtyxlayer')
  if (tdtyx) {
    tdtyx.setSource(
      new XYZ({
        wrapX: false,
        url: 'http://mapcache.tsingnormal.com:6688/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=50b117fa2f96eb1bf7c84b1365c2b548'
      })
    )
  }

  var tdtbz = ol2d.getLayerById('tdtbzlayer')
  if (tdtbz) {
    tdtbz.setSource(
      new XYZ({
        wrapX: false,
        url: 'http://mapcache.tsingnormal.com:6688/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=50b117fa2f96eb1bf7c84b1365c2b548'
      })
    )
  }

  const query = {
    tablename: 'geo_guo_polygon' //表名
  }

  var guoStyle = new Style({
    stroke: new Stroke({
      color: 'rgba(252, 184, 196, 0.9)',
      width: 2
      // lineDash: [20, 10, 20, 10],
    })
  })
  var guoOptions = {
    id: 'guolayer',
    ol2d: ol2d,
    query: query,
    style: guoStyle,
    isFit: true
  }
  maputils.AddMapLayer(guoOptions)

  // const style = new Style({
  //   fill: new Fill({
  //     color: "black",
  //   }),
  // });

  // // var f = new Feature(new MultiPolygon(coords));
  // var f = resultFeatures[0];
  // var crop = new Crop({
  //   feature: f,
  //   wrapX: true,
  //   inner: false,
  //   shadowWidth: 10,
  // });
  // // tdtdt.addFilter(crop);

  // var mask = new Mask({
  //   feature: f,
  //   wrapX: true,
  //   inner: false,
  //   // shadowWidth: 10,
  //   fill: new Fill({ color: [255, 255, 255, 1.0] }),
  // });
  //
  // tmpLayer.addFilter(crop);
  // tdtdt.addFilter(mask);
  // tdtbz.addFilter(mask);
  // tdtyx.addFilter(mask);
}

// 创建一个地图管理层

class MapManager {
  constructor() {
    this.currentLayer = null // 当前加载的图层
    this.instance = null
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new MapManager()
    }
    return this.instance
  }

  // 加载地图源
  loadMapSource(type) {
    let layer
    switch (type) {
      case 'tianditu':
        layer = this.createTiandituLayer()
        break
      case 'tianditu-vec':
        layer = this.createTiandituVecLayer()
        break
      case 'tianditu-mark':
        layer = this.createTiandituLayerMark()
        break
      case 'baidu':
        layer = this.createBaiduLayer()
        break
      case 'gaode-vec':
        layer = this.createGaodeVecLayer()
        break
      case 'gaode-mark':
        layer = this.createGaodeLayerMark()
        break
      case 'gaode':
        layer = this.createGaodeLayer()
        break
      case 'osm':
        layer = this.createOsmLayer()
        break
      case 'arcgis':
        layer = this.createArcgis()
      case 'google':
        layer = this.createGoogle()
        break

      // 可以根据需要添加更多类型的图层加载方法
      default:
        throw new Error('Unsupported map source type')
    }

    if (this.currentLayer) {
      if (Array.isArray(this.currentLayer)) {
        for (const item of this.currentLayer) {
          map.removeLayer(item)
        }
      } else {
        map.removeLayer(this.currentLayer)
      }
    }

    if (Array.isArray(layer)) {
      for (const item of layer) {
        item.setZIndex(-100);
        map.addLayer(item)
      }
    } else {
      layer.setZIndex(-100);
      map.addLayer(layer)
    }
    this.currentLayer = layer
  }
  //天地图地图
  createTiandituVecLayer() {
    const projection = get('EPSG:4326')

    var map_img = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        projection: projection,
        url: `http://t{0-7}.tianditu.gov.cn/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=${config.TDTTK}`,
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })

    var map_cta = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: `http://t4.tianditu.com/DataServer?T=cva_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
        crossOrigin: 'anonymous'
      })
    })
    return [map_img, map_cta]
  }
  //天地图影像
  createTiandituLayer() {
    const projection = get('EPSG:3857')
    return new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        projection: projection,
        url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
  }

  //天地图影像标注
  createTiandituLayerMark() {
    const projection = get('EPSG:3857')
    var a = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        projection: projection,
        url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })

    var map_cta = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: `http://t4.tianditu.com/DataServer?T=cva_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
        crossOrigin: 'anonymous'
      })
    })

    return [a, map_cta]
  }

  // 创建高德图层
  createGaodeVecLayer() {
    return new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
  }
  createGaodeLayer() {
    return new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
  }
  createGaodeLayerMark() {
    var a = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
    var b = new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: 'http://webst02.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
    return [a, b]
  }
  //

  // 创建百度图层
  createBaiduLayer() {

    // 创建百度地图的source
const baiduSource = new TileImage({
  projection: 'EPSG:3857',
  crossOrigin: 'anonymous',
  tileGrid: new TileGrid({
    origin: [0, 0],
    resolutions: Array.from({ length: 19 }, (_, i) => Math.pow(2, 18 - i))
  }),
  tileUrlFunction: function (tileCoord) {
    if (!tileCoord) return '';
    let z = tileCoord[0];
    let x = tileCoord[1];
    let y = -tileCoord[2] - 1; 
    // 对编号xy处理
    let baiduX = x < 0? 'M' + -x : x;
    let baiduY = y < 0? 'M' + -y : y;
    return 'http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=' +
      baiduX + '&y=' + baiduY + '&z=' + z + '&styles=pl&udt=20151021&scaler=1&p=1';
  }
});
    return new TileLayer({
      id: 'ditu-1',
      source: baiduSource
    })
  }

  // 创建OSM图层
  createOsmLayer() {
    return new OSM()
  }

  createArcgis() {
    return new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url:
          'http://server.arcgisonline.com/ArcGIS/rest/services/' +
          'World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
        crossOrigin: 'anonymous'
      })
    })
  }

  createGoogle() {
    return new TileLayer({
      id: 'ditu-1',
      source: new XYZ({
        url: 'http://0414.gggis.com/maps/vt?lyrs=s&x={x}&y={y}&z={z}',
        crossOrigin: 'anonymous',
        wrapX: false
      })
    })
  }
  // // 卸载当前地图源（实际上是移除当前图层）
  // unloadCurrentMapSource() {
  //   if (this.currentLayer) {

  //     if (Array.isArray(this.currentLayer)) {
  //       for (const e of this.currentLayer) {
  //         map.removeLayer(e);
  //       }
  //     } else {
  //       map.removeLayer(this.currentLayer);
  //     }
  //     this.currentLayer = null;
  //   }
  // }
}

// 稍后，你可以卸载当前图层并加载另一个
// mapManager.unloadCurrentMapSource();
// var baiduOptions = { ... }; // 百度地图的配置
// mapManager.loadMapSource(baiduOptions);

export { initMap, loadAllLayers, MapManager, loadFilterLayer,loadEarthQuakeYXC, delEarthQuakeYXC,initOtherMap }
